package com.isoftstone.project.tool.code.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.isoftstone.common.utils.text.Convert;
import com.isoftstone.framework.controller.BaseController;
import com.isoftstone.framework.domain.Page;
import com.isoftstone.framework.domain.PageData;
import com.isoftstone.framework.domain.Tidings;
import com.isoftstone.project.tool.code.domain.GenTable;
import com.isoftstone.project.tool.code.domain.GenTableColumn;
import com.isoftstone.project.tool.code.service.IGenTableColumnService;
import com.isoftstone.project.tool.code.service.IGenTableService;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
 * 代码生成 操作处理
 *
 * @author ruoyi
 */
@Controller
@RequestMapping("/tool")
public class GenController extends BaseController {
    private String prefix = "tool";

    @Autowired
    private IGenTableService genTableService;

    @Autowired
    private IGenTableColumnService genTableColumnService;

    @GetMapping("/table")
    public String gen() {
        return prefix + "/table_list";
    }

    /**
     * 查询代码生成列表
     */
    @PostMapping("/getTablelist")
    @ResponseBody
    public Object genList(Page page) {

        PageData pd = this.getPageData();
        page.setPd(pd);

        List<GenTable> balances = genTableService.selectGenTablelistPage(page);

        return Tidings.success(page.getTotalResult(), balances);
    }

    /**
     * 查询数据库列表
     */
    @PostMapping("/db/list")
    @ResponseBody
    public Object dataList(Page page) {

        PageData pd = this.getPageData();
        page.setPd(pd);

        List<GenTable> list = genTableService.selectDbTablelistPage(page);

        return Tidings.success(page.getTotalResult(),list);
    }

    /**
     * 查询数据表字段列表
     */
    @PostMapping("/column/list")
    @ResponseBody
    public Object columnList(GenTableColumn genTableColumn) {
        Object dataInfo = new Object();
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(genTableColumn);
        return Tidings.success(list);

    }

    /**
     * 导入表结构
     */
    @GetMapping("/importTable")
    public String importTable() {
        return prefix + "/table_import";
    }

    /**
     * 导入表结构（保存）
     */
    @PostMapping("/importTable")
    @ResponseBody
    public Object importTableSave(String tables) {
        String[] tableNames = Convert.toStrArray(tables);
        // 查询表信息
        List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
        genTableService.importGenTable(tableList,"tableNames");
        return Tidings.success();
    }

    /**
     * 修改代码生成业务
     */
    @GetMapping("/editTable")
    public String edit(Long tableId, ModelMap mmap) {
        if(tableId != null){
            GenTable table = genTableService.selectGenTableById(tableId);
            mmap.put("table", table);
        }
        return prefix + "/table_edit";
    }

    /**
     * 修改保存代码生成业务
     */
    @PostMapping("/edit")
    @ResponseBody
    public Object editSave(@Validated GenTable genTable) {
        genTableService.validateEdit(genTable);
        genTableService.updateGenTable(genTable);
        return Tidings.success();

    }


    @PostMapping("/deleteTable")
    @ResponseBody
    public Object remove(String tableId) {
        genTableService.deleteGenTableByIds(tableId);
        return Tidings.success();
    }

    /**
     * 预览代码
     */
    @RequiresPermissions("tool:gen:preview")
    @GetMapping("/preview/{tableId}")
    @ResponseBody
    public Object preview(@PathVariable("tableId") Long tableId) throws IOException {
        Map<String, String> dataMap = genTableService.previewCode(tableId);
        return Tidings.success(dataMap);
    }

    /**
     * 生成代码（下载方式）
     */
    @GetMapping("/download/{tableName}")
    public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException {
        byte[] data = genTableService.downloadCode(tableName);
        genCode(response, data);
    }

    /**
     * 生成代码（自定义路径）
     */

    @GetMapping("/createCode")
    @ResponseBody
    public void genCode(String tableName) {
        genTableService.generatorCode(tableName);
    }

    /**
     * 同步数据库
     */

    @GetMapping("/synchDb/{tableName}")
    @ResponseBody
    public void synchDb(@PathVariable("tableName") String tableName) {
        genTableService.synchDb(tableName);
    }

    /**
     * 批量生成代码
     */
    @GetMapping("/batchGenCode")
    @ResponseBody
    public void batchGenCode(HttpServletResponse response, String tables) throws IOException {
        String[] tableNames = Convert.toStrArray(tables);
        byte[] data = genTableService.downloadCode(tableNames);
        genCode(response, data);
    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException {
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"ruoyi.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}